package com.taptech.doufu.ui.fragment;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.CpLibListActivity;
import com.taptech.doufu.ui.adapter.CpLibsAdapter;
import com.taptech.doufu.bean.CPLibBean;
import com.taptech.doufu.ui.view.IndexView;
import com.taptech.doufu.services.CpService;
import com.taptech.doufu.util.ItemClickSupport;

import java.util.ArrayList;

/**
 * cp lib list view
 */
public class CpLibListFragment extends Fragment {

    private RecyclerView rvContacts;
    private ArrayList<CPLibBean> cplibs;

    private IndexView mIndexView;




    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.cp_lib_list_fragment, container, false);
        initView(rootView);
        initData();

        return rootView;
    }

    private void initView(View rootView) {
        rvContacts = (RecyclerView) rootView.findViewById(R.id.rv_contacts);
        rvContacts.setLayoutManager(new LinearLayoutManager(getActivity()));
        mIndexView = (IndexView) rootView.findViewById(R.id.index_view);


    }

    private void initData() {
        cplibs = getArguments().getParcelableArrayList(CpLibListActivity.CPLIBDATA);
        if (cplibs != null) {
            setAdapterData();
        }
    }
    private void setAdapterData() {
        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        rvContacts.setLayoutManager(llm);
        rvContacts.setAdapter(new CpLibsAdapter(cplibs, R.layout.item_cp_gay_libs_item, getActivity()));
        ItemClickSupport.addTo(rvContacts).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                cplibs.get(position).getIndex();
                CpService.enterCpDesActivity(getActivity(),cplibs.get(position).getId());
            }
        });

        mIndexView.setListener(new IndexView.OnIndexSelectListener() {
            @Override
            public void onItemSelect(int position, String value) {
                for (int i = 0; i< cplibs.size(); i++) {
                    if (cplibs.get(i).getIndex().equals(value)) {
                        ((LinearLayoutManager) rvContacts.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
        });
    }
}


